package customer

import (
	"counter-help/admin/server/global"
	"counter-help/admin/server/model/customer"
    customerReq "counter-help/admin/server/model/customer/request"
)

type CusSpreadService struct {}

// CreateCusSpread 创建cusSpread表记录
// Author [piexlmax](https://github.com/piexlmax)
func (cusSpreadService *CusSpreadService) CreateCusSpread(cusSpread *customer.CusSpread) (err error) {
	err = global.GVA_DB.Create(cusSpread).Error
	return err
}

// DeleteCusSpread 删除cusSpread表记录
// Author [piexlmax](https://github.com/piexlmax)
func (cusSpreadService *CusSpreadService)DeleteCusSpread(ID string) (err error) {
	err = global.GVA_DB.Delete(&customer.CusSpread{},"id = ?",ID).Error
	return err
}

// DeleteCusSpreadByIds 批量删除cusSpread表记录
// Author [piexlmax](https://github.com/piexlmax)
func (cusSpreadService *CusSpreadService)DeleteCusSpreadByIds(IDs []string) (err error) {
	err = global.GVA_DB.Delete(&[]customer.CusSpread{},"id in ?",IDs).Error
	return err
}

// UpdateCusSpread 更新cusSpread表记录
// Author [piexlmax](https://github.com/piexlmax)
func (cusSpreadService *CusSpreadService)UpdateCusSpread(cusSpread customer.CusSpread) (err error) {
	err = global.GVA_DB.Model(&customer.CusSpread{}).Where("id = ?",cusSpread.ID).Updates(&cusSpread).Error
	return err
}

// GetCusSpread 根据ID获取cusSpread表记录
// Author [piexlmax](https://github.com/piexlmax)
func (cusSpreadService *CusSpreadService)GetCusSpread(ID string) (cusSpread customer.CusSpread, err error) {
	err = global.GVA_DB.Where("id = ?", ID).First(&cusSpread).Error
	return
}

// GetCusSpreadInfoList 分页获取cusSpread表记录
// Author [piexlmax](https://github.com/piexlmax)
func (cusSpreadService *CusSpreadService)GetCusSpreadInfoList(info customerReq.CusSpreadSearch) (list []customer.CusSpread, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&customer.CusSpread{})
    var cusSpreads []customer.CusSpread
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.StartCreatedAt !=nil && info.EndCreatedAt !=nil {
     db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
    }
	err = db.Count(&total).Error
	if err!=nil {
    	return
    }

	if limit != 0 {
       db = db.Limit(limit).Offset(offset)
    }
	
	err = db.Find(&cusSpreads).Error
	return  cusSpreads, total, err
}